package com.example.mqtt.utils;

import com.alibaba.fastjson.JSON;
import com.example.mqtt.doman.dto.MqttMessageDTO;
import com.example.mqtt.provider.IMqttMessageGateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
@Order
@Slf4j
@Component
public class MqttSendUtil {
    protected static IMqttMessageGateway mqttMessageGateway;

    @Autowired(required = false)
    public void setMqttMessageGateway(IMqttMessageGateway mqttMessageGateway) {
        MqttSendUtil.mqttMessageGateway = mqttMessageGateway;
    }

    public static void sendMessage(String topic, byte[] payload) {
        try {
            if (mqttMessageGateway==null) {
                return;
            }
            mqttMessageGateway.publish(topic,payload);
        }catch (Exception e) {
            log.error("mqtt消息发送异常",e);
        }
    }

    public static void sendMessage(String topic, String payload) {
        sendMessage(topic, payload.getBytes(StandardCharsets.UTF_8));
    }

    public static<T> void sendMessage(String topic, MqttMessageDTO payload) {
        String message = JSON.toJSONString(payload);
        sendMessage(topic, message.getBytes(StandardCharsets.UTF_8));
    }
    public static void sendMessage(String topic,int qos, byte[] payload) {
        try {
            if (mqttMessageGateway==null) {
                return;
            }
            mqttMessageGateway.publish(topic,payload,qos);
        }catch (Exception e) {
            log.error("mqtt消息发送异常",e);
        }
    }

    public static void sendMessage(String topic,int qos, String payload) {
        sendMessage(topic,qos,payload.getBytes(StandardCharsets.UTF_8));
    }

    public static<T> void sendMessage(String topic,int qos,MqttMessageDTO payload) {
        String message = JSON.toJSONString(payload);
        sendMessage(topic,qos,message.getBytes(StandardCharsets.UTF_8));
    }
}
